package com.deep.deepenterprise.api.interceptor;

import com.deep.deepenterpise.common.code.DrCodeMsg;
import com.deep.deepenterpise.common.result.DrResult;
import com.deep.deepenterpise.common.DrGson;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author xyz
 * @version 1.0
 * @title BaseAccessInterceptor
 * @description
 * @create 2024/4/28 15:16
 */
public class DrBaseAccessInterceptor {
    private static final String UNKNOWN = "unknown";

    /**
     * @Auth xyz
     * @Desc //TODO 渲染错误信息，错误信息格式：{"code": 10001, "msg": "系统繁忙，请稍后再试"}
     * @Time 09:27 2024/4/22
     * @Param [response, sessionError]
     */
    public void render(HttpServletResponse response, DrCodeMsg sessionError) throws IOException {
        response.setContentType("application/json");
        ServletOutputStream outputStream = response.getOutputStream();
        String str = DrGson.toJSONString(DrResult.error().code(sessionError.getCode()).message(sessionError.getMsg()));
        outputStream.write(str.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }

    /**
     * @return java.lang.String
     * @Auth xyz
     * @Desc //TODO 获取IP地址
     * @Time 14:30 2024/4/24
     * @Param [request]
     */
    public String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
